package com.ysd.util;

import io.swagger.annotations.ApiOperation;

import javax.servlet.http.HttpServletRequest;
import java.net.InetAddress;
import java.util.HashMap;
import java.util.Map;

public class ComputerInfo {


    @ApiOperation(value = "获取电脑信息")
    public  static   Map<String, Object> getComputerInfo(HttpServletRequest request)  throws Exception{
        Map<String, Object> dataMap = new HashMap<>();
        dataMap.put("ip", getIpAddress(request));
        InetAddress inetAddress = InetAddress.getByName(getIpAddress(request));
        String computername = inetAddress.getHostName();
        if ("localhost".equalsIgnoreCase(computername)) {
            computername = InetAddress.getLocalHost().getCanonicalHostName();
        }
        String[] split = computername.split("\\.");
        String name = split[0].toUpperCase();
        dataMap.put("name",name);
        return  dataMap;
    }

    //传入request对象，获得客户端ip
    //注意，本地不行，本地会获取到0:0:0:0:0:0:0:1；服务器上是正常的
    public static String getIpAddress(HttpServletRequest request) {
        String ip = request.getHeader("x-forwarded-for");
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            //本地会获取到0:0:0:0:0:0:0:1
            ip = request.getRemoteAddr();
        }
        if (ip.contains(",")) {
            return ip.split(",")[0];
        } else {
            return ip;
        }
    }

}
